package com.yunmang.activity.ordermanager;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.activity.SearchEndActivity;
import com.yunmang.activity.kaipiaoActivity;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.GoodsBean;
import com.yunmang.entity.MemberBean;
import com.yunmang.entity.NameBean;
import com.yunmang.entity.OrderDetailBean;
import com.yunmang.entity.ParameterEntity.EditBillBean;
import com.yunmang.entity.event.EndEvent;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;
import com.yunmang.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import HPRTAndroidSDK.HPRTPrinterHelper;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/6/22.
 */
public class UpdateAndPrintActivity extends BaseActivity implements OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.et_hdbh_search)
    EditText etHdbhSearch;
    @InjectView(R.id.image_scan)
    ImageView imageScan;
    @InjectView(R.id.search)
    Button search;
    @InjectView(R.id.et_hdbh)
    EditText etHdbh;
    @InjectView(R.id.et_zd_station)
    TextView etZdStation;
    @InjectView(R.id.et_zz_station)
    EditText etZzStation;
    @InjectView(R.id.et_card_number)
    EditText etCardNumber;
    @InjectView(R.id.et_fh_number)
    EditText etFhNumber;
    @InjectView(R.id.et_fh_name)
    EditText etFhName;
    @InjectView(R.id.et_sh_number)
    EditText etShNumber;
    @InjectView(R.id.et_sh_name)
    EditText etShName;
    @InjectView(R.id.tv_shd_address)
    TextView tvShdAddress;
    @InjectView(R.id.et_sh_address)
    EditText etShAddress;
    @InjectView(R.id.et_cargo_name)
    EditText etCargoName;
    @InjectView(R.id.spinner_pack)
    TextView spinnerPack;
    @InjectView(R.id.cargo_number)
    EditText cargoNumber;
    @InjectView(R.id.et_cargo_quality)
    EditText etCargoQuality;
    @InjectView(R.id.et_cargo_bulk)
    EditText etCargoBulk;
    @InjectView(R.id.iv_balance)
    TextView ivBalance;

    @InjectView(R.id.et_zz_money)
    EditText etZzMoney;
    @InjectView(R.id.et_cargo_freight)
    EditText etCargoFreight;
    @InjectView(R.id.et_delivery_charge)
    EditText etDeliveryCharge;
    @InjectView(R.id.et_collect_money)
    EditText etCollectMoney;
    @InjectView(R.id.et_insure_fare)
    EditText etInsureFare;
    @InjectView(R.id.et_rebates)
    EditText etRebates;
    @InjectView(R.id.et_note_number)
    EditText etNoteNumber;
    @InjectView(R.id.ll_biaoqian)
    LinearLayout llBiaoqian;
    @InjectView(R.id.tv_reason)
    TextView tvReason;
    @InjectView(R.id.et_remark)
    EditText etRemark;
    @InjectView(R.id.ll_bottom)
    LinearLayout llBottom;
    @InjectView(R.id.fab)
    FloatingActionButton fab;
    @InjectView(R.id.rl_detail)
    RelativeLayout rlDetail;
    @InjectView(R.id.et_date)
    TextView etDate;
    @InjectView(R.id.tv_delivery_station)
    TextView tvDeliveryStation;
    @InjectView(R.id.rb_ziti)
    RadioButton rbZiti;
    @InjectView(R.id.rb_sh)
    RadioButton rbSh;
    @InjectView(R.id.rg_is_receipt)
    RadioGroup rgIsReceipt;
    @InjectView(R.id.rb_yes_huidan)
    RadioButton rbYesHuidan;
    @InjectView(R.id.rb_no_huidan)
    RadioButton rbNoHuidan;
    @InjectView(R.id.spinner_count_style)
    TextView spinnerCountStyle;
    @InjectView(R.id.et_baoe)
    EditText etBaoe;
    private Subscriber<OrderDetailBean> subscriber;
    private Subscriber mSubScriber;
    private int endId, memberid, balance;
    private String[] packArray, balanceArray;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static HPRTPrinterHelper HPRTPrinter = new HPRTPrinterHelper();
    private boolean isTagprint = true, isReceiptPrint = true;//是否打印标签
    private String receipt_printer_style, tag_printer_style;//打印机类型
    public static BluetoothAdapter myBluetoothAdapter;
    private ScanReceiver scanReceiver=new ScanReceiver();
    private String originallhdbh;//原始hdbh
    @Override
    public int getLayoutId() {
        return R.layout.activity_bulu_manager;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        initToolbar();
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("运单修改");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        etCardNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String card = etCardNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(card)) {
                        getMemberInfo(card);
                    }
                }
            }
        });
        etFhNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String shipper = etFhNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(shipper)) {
                        getShipperName(shipper);

                    }
                }
            }
        });
        etShNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String consignee = etShNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(consignee)) {
                        getConsigneeName(consignee);
                    }
                }
            }
        });
        cargoNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                etNoteNumber.setText(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        packArray = getResources().getStringArray(R.array.pack);
        //结算方式
        balanceArray = getResources().getStringArray(R.array.balance);
        spinnerPack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fillPack(packArray);
            }
        });
    }

    private OrderDetailBean.ModelBean model;
    private OrderDetailBean.ModelBean.BillBean bill;
    private OrderDetailBean.ModelBean.ContactBean contact;
    private OrderDetailBean.ModelBean.CostBean cost;
    private OrderDetailBean.ModelBean.GoodsListBean goodsListBean;
    private OrderDetailBean.ModelBean.TransportBean transport;

    private void fillUI(OrderDetailBean orderDetailBean) {
        model = orderDetailBean.getModel();
        bill = model.getBill();
        contact = model.getContact();
        cost = model.getCost();
        goodsListBean = model.getGoodsList().get(0);
        transport = model.getTransport();
        etDate.setText(bill.getBillDate().substring(0, 10));
        tvDeliveryStation.setText(model.getStartDepartName());
        etHdbh.setText(bill.getHdbh());
        etZdStation.setText(model.getEndDepartName());
        etZzStation.setText(model.getTransferDepartName() == null ? "" : model.getTransferDepartName().toString());
        etCardNumber.setText(model.getMemberCode() == null || model.getMemberCode().equals("无") ? "" : model.getMemberCode().toString());
        etFhName.setText(contact.getShipper());
        etFhNumber.setText(contact.getShipperPhone());
        etShName.setText(contact.getConsignee());
        etShNumber.setText(contact.getConsigneePhone());
        etShAddress.setText(contact.getConsigneeAddress() == null ? "" : contact.getConsigneeAddress().toString());
        etCargoName.setText(goodsListBean.getGoodsName());
        spinnerPack.setText(goodsListBean.getPack() == null ? "" : goodsListBean.getPack().toString());
        cargoNumber.setText(goodsListBean.getNumbers() + "");
        etCargoQuality.setText(goodsListBean.getWeight() + "");
        etCargoBulk.setText(goodsListBean.getCubage() + "");
        spinnerCountStyle.setText(model.getDisplayBalanceMethod());
        etCargoFreight.setText(cost.getTransportCost() + "");
        etDeliveryCharge.setText(cost.getDeliveryCost() + "");
        etCollectMoney.setText(cost.getGoodsCost() + "");
        etZzMoney.setText(cost.getTransferCost()+"");
        etRemark.setText(bill.getNotes());
        etBaoe.setText(goodsListBean.getPremiumAmount()+"");
        if (bill.getTakeMethod().trim().equals("自提"))
            rbZiti.setChecked(true);
        else
            rbSh.setChecked(true);
        bm = cost.getBalanceMethod();
        endId = transport.getEndDepartment();
    }

    private void getOrderDetail(String search) {
        showWaitingDialog("数据获取中……");
        subscriber = new Subscriber<OrderDetailBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                rlDetail.setVisibility(View.GONE);
                showToast("获取失败");
                hideWaitingDialog();
            }

            @Override
            public void onNext(OrderDetailBean orderDetailBean) {
                hideWaitingDialog();
                if (orderDetailBean.getCode() == 200) {
                    rlDetail.setVisibility(View.VISIBLE);
                    fillUI(orderDetailBean);
                } else {
                    rlDetail.setVisibility(View.GONE);
                    showToast("无数据");
                }
            }
        };
        HttpUtils.getInstance().getOrderDetail(subscriber, search, AppConstant.orgInfo.getId() + "");
    }


    @OnClick({R.id.et_zd_station, R.id.spinner_count_style, R.id.image_scan, R.id.search, R.id.fab})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_zd_station:
                startActivity(new Intent(context, SearchEndActivity.class));
                break;
            case R.id.image_scan:
                CommonUtils.onScanBarcode(this);
                break;
            case R.id.spinner_count_style:
                fillBalanceStyle(balanceArray);
                break;
            case R.id.fab:
                if(model.isCanEdit()){
                    setmConfirmAlert();
                }else{
                    showAlertDialog("该票不能进行修改");
                }

                break;
            case R.id.search:
                String search = CommonUtils.getTextViewValue(etHdbhSearch);
                if (TextUtils.isEmpty(search)) {
                    showToast("请输入单号");
                    return;
                }
                getOrderDetail(search);
                break;
        }
    }

    /**
     * 获取会员卡信息
     *
     * @param code 10014
     */
    private void getMemberInfo(String code) {
        showWaitingDialog("正在获取……");
        mSubScriber = new Subscriber<MemberBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                clearEditInfo(etCardNumber);
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(MemberBean memberBean) {
                hideWaitingDialog();
                if (memberBean.getCode() == 200) {
                    if (memberBean.getModel() != null) {
                        etFhNumber.setText(memberBean.getModel().getTelephone());
                        etFhName.setText(memberBean.getModel().getName());
                        memberid = memberBean.getModel().getId();
                    } else {
                        clearEditInfo(etCardNumber);
                        showToast("暂无该卡号");
                    }
                } else {
                    clearEditInfo(etCardNumber);
                    showToast(memberBean.getMessage().toString());
                }
            }
        };
        HttpUtils.getInstance().getMemberInfo(mSubScriber, code);
    }

    /**
     * 获取发货人姓名
     *
     * @param consigneeName
     */
    private void getConsigneeName(String consigneeName) {
        mSubScriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(NameBean nameBean) {
                if (nameBean.getCode() == 200) {
                    if (nameBean.getModel() != null) {
                        etShName.setText(nameBean.getModel());
                    } else {
                    }
                } else {
                }
            }

        };
        HttpUtils.getInstance().getConsignee(mSubScriber, consigneeName);
    }

    private void getShipperName(String shipperNumber) {
        mSubScriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(NameBean nameBean) {
                if (nameBean.getCode() == 200) {
                    if (!TextUtils.isEmpty(nameBean.getModel())) {
                        etFhName.setText(nameBean.getModel());
                    } else {
                    }
                } else {
                }
            }
        };
        HttpUtils.getInstance().getshipper(mSubScriber, shipperNumber);
    }
    private int bm;
    private String constract() {

        Gson gson = new Gson();
        EditBillBean bean = new EditBillBean();
        bean.setId(bill.getId());
        bean.setHdbh(bill.getHdbh());
        bean.setEndDepartmentId(endId);
        bean.setShipper(CommonUtils.getTextViewValue(etFhName));
        bean.setShipperPhone(CommonUtils.getTextViewValue(etFhNumber));
        bean.setConsignee(CommonUtils.getTextViewValue(etShName));
        bean.setConsigneePhone(CommonUtils.getTextViewValue(etShNumber));
        bean.setMemberNo(CommonUtils.getTextViewValue(etCardNumber));
        bean.setTransportCost(Double.valueOf(CommonUtils.getTextViewValue(etCargoFreight)));
        bean.setGoodsCost(Double.valueOf(CommonUtils.getTextViewValue(etCollectMoney)));

        bean.setBalanceMethod(bm);
        bean.setDeliveryCost(Double.valueOf(CommonUtils.getTextViewValue(etDeliveryCharge)));
        bean.setUserId(Integer.parseInt(AppConstant.userid));
        String method;
        if (rbZiti.isChecked()) {
            method = "自提";
        } else {
            method = "送货";
        }
        bean.setTakeMethod(method);
        bean.setApplyReason(CommonUtils.getTextViewValue(etRemark));
        List<GoodsBean>  list=new ArrayList<>();
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setGoodsName(CommonUtils.getTextViewValue(etCargoName));
        goodsBean.setPack(CommonUtils.getTextViewValue(spinnerPack));
        goodsBean.setNumbers(CommonUtils.getTextViewValue(cargoNumber));
        String baoe="0";
        if(!TextUtils.isEmpty(CommonUtils.getTextViewValue(etBaoe))){
            baoe=CommonUtils.getTextViewValue(etBaoe);
        }
        goodsBean.setPremiumAmount(baoe);
        goodsBean.setCubage(CommonUtils.getTextViewValue(etCargoBulk));
        goodsBean.setWeight(CommonUtils.getTextViewValue(etCargoQuality));
        goodsBean.setId(goodsListBean.getId());
        list.add(goodsBean);
        bean.setGoodsList(list);
        return gson.toJson(bean);
    }

    private void submitData(String inJson) {
        showWaitingDialog("数据提交中……");
        mSubScriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                showAlertDialog("修改异常");
                e.printStackTrace();

            }

            @Override
            public void onNext(NameBean nameBean) {
                hideWaitingDialog();
                if (nameBean.getCode() == 200) {
                    String model = nameBean.getModel();
                    if (model.equals("true")) {
                        //执行打印
                        actionTagByHanYin();
                        showAlertDialog("修改成功");
                    } else {
                        showAlertDialog("提交成功，需要进行审批");
                    }
                } else {
                    showAlertDialog("修改失败");
                }
            }
        };
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), inJson);
        HttpUtils.getInstance().editBill(mSubScriber, body);
    }

    /**
     * 弹出对话框
     *
     * @param string
     */
    private void showAlertDialog(String string) {
        new AlertView("提示", string, null, new String[]{"确定"}, null, this, AlertView.Style.Alert, this).show();
    }


    private AlertView packAlertView, mConfirmAlert, balanceAlertView;

    private void setmConfirmAlert() {
        mConfirmAlert = new AlertView("提示", "确定要保存数据", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this);
        mConfirmAlert.setCancelable(true).show();
    }

    private void fillBalanceStyle(String[] balanceArray) {
        balanceAlertView = new AlertView(null, null, null, null, balanceArray, this, AlertView.Style.Alert, this);
        balanceAlertView.show();
    }

    private void fillPack(String[] stringArray) {
        packAlertView = new AlertView(null, null, null, null, stringArray, this, AlertView.Style.Alert, this);
        packAlertView.show();
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == mConfirmAlert && position != AlertView.CANCELPOSITION) {

            if (etCardNumber.hasFocus()) {//如果有焦点
                String cd = etCardNumber.getText().toString().trim();
                if (!TextUtils.isEmpty(cd)) {
                    getMemberInfo(cd);
                }
            }
            submitData(constract());
        } else if (o == packAlertView && position != AlertView.CANCELPOSITION) {
            spinnerPack.setText(packArray[position]);
        } else if (o == balanceAlertView && position != AlertView.CANCELPOSITION) {
            spinnerCountStyle.setText(balanceArray[position]);
            bm=CommonUtils.getBalanceMethod(balanceArray[position]);
        }
    }

    public void onEventMainThread(EndEvent event) {
        endId = event.getId();
        etZdStation.setText(event.getName());
    }

    private void actionTagByHanYin() {
        if (!HPRTPrinterHelper.IsOpened()) {
            tryconnect(CommonUtils.getTextViewValue(etHdbh));
        } else {
            PrintSampleReceipt(CommonUtils.getTextViewValue(etHdbh));
        }
    }

    private void tryconnect(String model) {
        boolean hasConnected = false;
        hasConnected = ConnectDevice();
        if (hasConnected) {
            DisConnect();
        }
        if (hasConnected) {
            showToast("连接成功");
            kaipiaoActivity.HPRTPrinter = new HPRTPrinterHelper(this, "HM-T300");
            try {
                if (HPRTPrinterHelper.PortOpen("Bluetooth," + SharedPreferencesUtils.getParameter(this, "SelectedTagMac")) == 0) {
                    PrintSampleReceipt(model);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showToast("连接失败");
        }
    }

    private void printOrder(String hdbh) {
        HPRTPrinterHelper.printAreaSize("0", "200", "600", "450", "1");
        HPRTPrinterHelper.LanguageEncode = "GBK";
        HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "150", "5", AppConstant.companyName + "运单");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "0", "180", "55", hdbh);
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "85", CommonUtils.getTextViewValue(tvDeliveryStation) + "-" + CommonUtils.getTextViewValue(etZdStation) + "  " + CommonUtils.getTextViewValue(cargoNumber) + "件");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "135", "发货人:" + CommonUtils.getTextViewValue(etFhName) + "  " + CommonUtils.getTextViewValue(etFhNumber));
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "185", "收货人:" + CommonUtils.getTextViewValue(etShName) + "  " + CommonUtils.getTextViewValue(etShNumber));
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "230", "运费:" + CommonUtils.getTextViewValue(etCargoFreight) + "  送货费：" + CommonUtils.getTextViewValue(etDeliveryCharge) + "  中转费：" + CommonUtils.getTextViewValue(etZzMoney));
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "280", "货款:" + CommonUtils.getTextViewValue(etCollectMoney));
        String str = rbZiti.isChecked() == true ? "" : "";
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "330", "时间：" + DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "  " + str + "  " + CommonUtils.getTextViewValue(spinnerCountStyle));
        HPRTPrinterHelper.Form();
        HPRTPrinterHelper.PrintData("POPRINT\r\n");
    }


    private void PrintSampleReceipt(String hdbh) {
        try {
            if (!HPRTPrinterHelper.IsOpened()) {
                showToast("请进行蓝牙连接");
                return;
            }
            int sumNum = CommonUtils.ChangeString2Int(cargoNumber);//总件数
            String tagnum = CommonUtils.getTextViewValue(etNoteNumber);
            if (!TextUtils.isEmpty(tagnum)) {
                sumNum = Integer.parseInt(tagnum);
                if (sumNum > 20) {
                    sumNum = 20;
                }
            }
            for (int i = 0; i <= sumNum; i++) {
                if (i == 0) {
                    printOrder(hdbh);
                    break;
                }
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
        }
    }

    private boolean ConnectDevice() {
        boolean bRet = false;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        myBluetoothAdapter.cancelDiscovery();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            // 4.0.3版本 经测试，高版本兼容低版本
            mmDevice = myBluetoothAdapter.getRemoteDevice(SharedPreferencesUtils.getParameter(this, "SelectedTagMac"));
            if (Build.VERSION.SDK_INT < 15) {
                mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            } else {
                mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            }
            myBluetoothAdapter.cancelDiscovery();
            Thread.sleep(100);
            if (myBluetoothAdapter.isDiscovering()) {
                int iCnt = 0;
                while (iCnt < 5) {
                    Thread.sleep(100);
                    iCnt++;
                    if (myBluetoothAdapter.cancelDiscovery()) {
                        break;
                    }
                }
            }
            mmSocket.connect();
        } catch (Exception e) {
            try {
                Method m;
                m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
                mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
                if (myBluetoothAdapter.isDiscovering()) {
                    int iCnt = 0;
                    while (iCnt < 5) {
                        Thread.sleep(100);
                        iCnt++;
                        if (myBluetoothAdapter.cancelDiscovery()) {
                            break;
                        }
                    }
                }
                mmSocket.connect();
            } catch (Exception e1) {
                Log.d("PRTLIB", (new StringBuilder("BTO_ConnectDevice --> create ")).append(e1.getMessage()).toString());
                return false;
            }
        }

        try {
            bRet = GetIOInterface();
            return bRet;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean GetIOInterface() {
        Log.d("PRTLIB", "BTO_GetIOInterface...");
        try {
            mmInStream = mmSocket.getInputStream();
            mmOutStream = mmSocket.getOutputStream();
        } catch (IOException e) {
            Log.d("PRTLIB", (new StringBuilder("BTO_GetIOInterface ")).append(e.getMessage()).toString());
            return false;
        }
        return true;
    }

    private InputStream mmInStream;
    private OutputStream mmOutStream;
    private BluetoothDevice mmDevice;
    private BluetoothSocket mmSocket;

    private boolean DisConnect() {
        boolean bRet = true;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (mmInStream != null) {
                mmInStream.close();
                mmInStream = null;
            }
            if (mmOutStream != null) {
                mmOutStream.close();
                mmOutStream = null;
            }
            if (mmSocket != null) {
                mmSocket.close();
                mmSocket = null;
            }
        } catch (IOException e) {
            System.out.println((new StringBuilder("BTO_ConnectDevice close ")).append(e.getMessage()).toString());
            bRet = false;
        }
        return bRet;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            } else {
                etHdbhSearch.setText(result.getContents().substring(0, result.getContents().length() - 3));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.android.server.scannerservice.broadcast")) {
                originallhdbh = intent.getStringExtra("scannerdata").trim();
            } else if (intent.getAction().equals("android.intent.action.SCANRESULT")) {
                originallhdbh = intent.getStringExtra("value").trim();
            }
            etHdbhSearch.setText(originallhdbh.substring(0,originallhdbh.length()-3));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.android.server.scannerservice.broadcast");
        filter.addAction("android.intent.action.SCANRESULT");
        registerReceiver(scanReceiver,filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterReceiver(scanReceiver);
    }

}
